package org.soma.sso.core.filter;


import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

public class SomaSsoTokenFilter extends HttpServlet implements Filter {

	/**
	 * serialVersionUID
	 */
	private static RestTemplate restTemplate = new RestTemplate();
	private static final long serialVersionUID = 5716474080011059081L;
	public static Logger logger = LoggerFactory.getLogger(SomaSsoTokenFilter.class);

	private String SSO_SERVER_URL;
	private String SSO_SERVER_VERIFY_URL;

	public void init(FilterConfig filterConfig) throws ServletException {
		SSO_SERVER_URL = filterConfig.getInitParameter("SSO_SERVER_URL");
		SSO_SERVER_VERIFY_URL = filterConfig
				.getInitParameter("SSO_SERVER_VERIFY_URL");
		if (StringUtils.isBlank(SSO_SERVER_URL)) {
			logger.error("SSO_SERVER_URL is null.");
		}
		if (StringUtils.isBlank(SSO_SERVER_VERIFY_URL)) {
			logger.error("SSO_SERVER_VERIFY_URL is null.");
		}
	}

	public void doFilter(ServletRequest servletRequest,	ServletResponse servletResponse, FilterChain chain)
		throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		
		
		
		String token =request.getParameter("token");
		 //请求中带有token，去sso-server验证token是否有效
		 String authority = null;
		if (StringUtils.isNotBlank(token)) {
			boolean verifyResult = this.verify(request, SSO_SERVER_VERIFY_URL,
					request.getParameter("token"));
			if (verifyResult) {
				chain.doFilter(request, response);
				return;
			} else {
				authority = "token->" + token	+ " is invalidate.";
			}
		}

		 HttpSession session = request.getSession();
		 if (session.getAttribute("login") != null) {
			chain.doFilter(request, response);
		    return;
		 }
		 //跳转至sso认证中心
		 String callbackURL = request.getRequestURL().toString();
		 StringBuilder url = new StringBuilder();
		 url.append(SSO_SERVER_URL).append("?callbackURL=").append(callbackURL);
		 if(authority != null) {
			 url.append("&authority=").append(authority);
		 }
		 response.sendRedirect(url.toString());

	}

	private boolean verify(HttpServletRequest request, String verifyUrl, String token) {
	        //获取header信息
	     HttpHeaders requestHeaders = new HttpHeaders();
	     Enumeration<String> headerNames = request.getHeaderNames();
	      while (headerNames.hasMoreElements()) {
	          String key = (String) headerNames.nextElement();
	          String value = request.getHeader(key);
	          requestHeaders.add(key, value);
	        }
	     HttpEntity<String> requestEntity = new HttpEntity<String>(null != null ? JSONObject.toJSONString(null) : null, requestHeaders);
	     ResponseEntity<String> result = restTemplate.exchange(verifyUrl + "?token=" + token, HttpMethod.POST, requestEntity, String.class);

		JSONObject ret = JSONObject.parseObject(result.getBody());
		if("success".equals(ret.getString("code"))) {
			return true;
		}
		logger.error(request.getRequestURL().toString() + " : " + ret.getString("msg"));
		return false;
	}


	public void destroy() {
		// TODO Auto-generated method stub

	}

}
